import type { Ref } from 'vue'

export default function (jsonData: Ref<any>, chooseIdx: Ref<number>, line: Ref<any>) {
  // 计算线段位置
  function computedLinesPosition() {
    let xline: number = 0
    let yline: number = 0
    const xs = []
    const ys = []
    const currentBlock = jsonData.value.blocks[chooseIdx.value]
    const { left: x, top: y, width: w, height: h } = currentBlock.style
    // 当前选中的的block计算变量
    const currentBlockXl = x - w / 2 //左
    const currentBlockXm = x //中
    const currentBlockXr = x + w / 2 //右
    const currentBlockYt = y - h / 2 //上
    const currentBlockYm = y //中
    const currentBlockYb = y + h / 2 //下
    for (let i = 0; i < jsonData.value.blocks.length; i++) {
      if (i === chooseIdx.value) {
        continue
      }
      const block = jsonData.value.blocks[i]
      const { left, top, width, height } = block.style
      // 当前循环的block计算变量
      const blockXl = left - width / 2 //左
      const blockXm = left //中
      const blockXr = left + width / 2 //右
      const blockYt = top - height / 2 //上
      const blockYm = top //中
      const blockYb = top + height / 2 //下
      xs.push(
        { show: abs(currentBlockXl, blockXl), distance: blockXl }, //左对左
        { show: abs(currentBlockXm, blockXl), distance: blockXl }, //中对左
        { show: abs(currentBlockXr, blockXl), distance: blockXl }, //右对左
        { show: abs(currentBlockXl, blockXm), distance: blockXm }, //左对中
        { show: abs(currentBlockXm, blockXm), distance: blockXm }, //中对中
        { show: abs(currentBlockXr, blockXm), distance: blockXm }, //右对中
        { show: abs(currentBlockXl, blockXr), distance: blockXr }, //左对右
        { show: abs(currentBlockXm, blockXr), distance: blockXr }, //中对右
        { show: abs(currentBlockXr, blockXr), distance: blockXr } //右对右
      )
      ys.push(
        { show: abs(currentBlockYt, blockYt), distance: blockYt }, //上对上
        { show: abs(currentBlockYm, blockYt), distance: blockYt }, //中对上
        { show: abs(currentBlockYb, blockYt), distance: blockYt }, //下对上
        { show: abs(currentBlockYt, blockYm), distance: blockYm }, //上对中
        { show: abs(currentBlockYm, blockYm), distance: blockYm }, //中对中
        { show: abs(currentBlockYb, blockYm), distance: blockYm }, //下对中
        { show: abs(currentBlockYt, blockYb), distance: blockYb }, //上对下
        { show: abs(currentBlockYm, blockYb), distance: blockYb }, //中对下
        { show: abs(currentBlockYb, blockYb), distance: blockYb } //下对下
      )
    }
    const d = 5
    for (let i = 0; i < xs.length; i++) {
      if (xs[i].show < d) {
        xline = xs[i].distance as number
        break
      }
    }
    for (let i = 0; i < ys.length; i++) {
      if (ys[i].show < d) {
        yline = ys[i].distance as number
        break
      }
    }
    line.value.x = xline
    line.value.y = yline
  }
  // 计算绝对值
  function abs(a: number, b: number) {
    return Math.abs(a - b)
  }
  return {
    computedLinesPosition
  }
}
